<template>
  <el-dropdown :type="buttonType" split-button :size="size" :disabled="disabled" @command="handleCommand">
      {{lockState.label}}
    <template #dropdown v-if="disabled==false">
      <el-dropdown-menu>
        <el-dropdown-item command="0">解除锁定</el-dropdown-item>
        <el-dropdown-item command="1">锁定</el-dropdown-item>
        <el-dropdown-item v-if="archivable" command="5">归档</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>


<script lang="ts" setup>
import { ref, watch, computed, onMounted, PropType } from 'vue'
import { ElMessage } from 'element-plus'
import { UPDATE_MODEL_EVENT } from '@/utils/constants'
import { AuthTag, DataLockState } from '@/common/AuthState'
type TargetElement = HTMLInputElement | HTMLTextAreaElement
const props = defineProps({
  dataId: {type:Object},
  masterLockState: {type:Number, default:0},
  lockState: {type:Number, default:0},
  authTag : {type:Number, default:0},//权限类型

  size:{type:String, default:'medium'},
  onChangeState:{type:Function as PropType<(dataId:any, newState:number)=>Promise<number>>, required: true}
});
const emit = defineEmits(['update:lockState', 'change']);

const lockState = ref({state:0, label:'未锁定'});

const buttonType=ref<any>("");

const disabled = computed(()=>{
  let masterLockState1 = props.masterLockState || 0;
  let alterable = false;
  if(DataLockState.unlocked(masterLockState1)){   //主数据没有被锁定  
    if(AuthTag.archivable(props.authTag) || (AuthTag.lockable(props.authTag) && lockState.value.state != 5)){//是否可以更改状态：true：有归档权限，或者 有锁定权限并且当前不是归档状态
      alterable = true;
    }
  }
  return !alterable;
});

const archivable = computed(()=>{
  return AuthTag.archivable(props.authTag);
});

// const lockable = computed(()=>{
//   return AuthTag.lockable(props.authTag);
// });

const handleCommand = async (stateStr:string)=>{
  let oldState = lockState.value.state;  
  let state = parseInt(stateStr);

  let respState;
  try{
    respState = await props.onChangeState(props.dataId, state);
  }catch{
    respState = oldState;
  }
  
  setLockState(respState);
  emit('update:lockState', respState);
  //emit(UPDATE_MODEL_EVENT, lockState);
  //emit('change', stateNum, oldState);
}

const setLockState = (state:number) => {
  if(1 == state){
    buttonType.value = "success";
    lockState.value.state = state;
    lockState.value.label = "已锁定"
  }else if(5 == state){
    buttonType.value = "warning";
    lockState.value.state = state;
    lockState.value.label = "已归档"
  }else{
    buttonType.value = "";
    lockState.value.state = 0;
    lockState.value.label = "未锁定"
  }
}

const propLockState = computed(() =>
  props.lockState === null || props.lockState === undefined
    ? 0
    : props.lockState
)

watch(propLockState, () => setLockState(props.lockState || 0))

onMounted(() => {
  setLockState(props.lockState || 0);
});

</script>
